package com.hanfengyi.course.service.impl;


        import com.alibaba.fastjson.JSON;
        import com.alibaba.fastjson.JSONObject;
        import com.baomidou.mybatisplus.service.impl.ServiceImpl;
        import com.hanfengyi.course.vo.CourseTypeVO;
        import com.hanfengyi.hrm.constants.RedisKeyConstants;
        import com.hanfengyi.course.domain.CourseType;
        import com.hanfengyi.course.mapper.CourseTypeMapper;
        import com.hanfengyi.course.service.ICourseTypeService;
        import com.hanfengyi.feign.RedisFeignClient;
        import com.hanfengyi.feign.StaticPageFignClient;
        import com.hanfengyi.hrm.AjaxResult;
        import org.apache.commons.lang.StringUtils;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Service;

        import java.io.Serializable;
        import java.util.*;

/**
 * <p>
 * 课程目录 服务实现类
 * </p>
 *
 * @author hfy
 * @since 2020-02-17
 */
@Service
public class CourseTypeServiceImpl extends ServiceImpl<CourseTypeMapper, CourseType> implements ICourseTypeService {
    @Autowired
    private RedisFeignClient redisFeignClient;
    @Autowired
    private StaticPageFignClient staticPageFignClient;

    /**
     * 触发静态页面生成
     */
    public void pageStaticAction(){
        //1. 查询数据放到redis中
        List<CourseType> courseTypes = treeData();
        Map<String,Object> map = new HashMap<>();
        //模板文件中需要的属性名字
        map.put("courseTypes", courseTypes);
        AjaxResult result = redisFeignClient.set(RedisKeyConstants.COURSE_TYPE_PAGE_STATIC, JSON.toJSONString(map));
        if(!result.isSuccess()){
            throw new RuntimeException("数据存储失败！");
        }
        String templateName = "home";
        //2. 通过feign调用页面静态化微服务
        AjaxResult ajaxResult = staticPageFignClient.pageStaticAction(RedisKeyConstants.COURSE_TYPE_PAGE_STATIC,templateName);
        if(!ajaxResult.isSuccess()){
            throw new RuntimeException("页面静态化失败！");
        }
    }

    /**
     *  把数据放到redis中
     * @return
     */
    private List<CourseType> putDataIntoRedis(){
        List<CourseType> allTypes = baseMapper.selectList(null);
        redisFeignClient.set(RedisKeyConstants.COURSE_TYPE, JSONObject.toJSONString(allTypes));
        return allTypes;
    }

    /**
     * 获得有层次结构的数据
     * @return
     */
    @Override
    public List<CourseType> treeData() {
        List<CourseType> allTypes = null;
        //1. 从redis中获取数据
        AjaxResult course_type = redisFeignClient.get(RedisKeyConstants.COURSE_TYPE);
        //2. 有数据转换为List
        if(course_type.isSuccess() && course_type.getResultObj()!=null){
            String courseTypeForJson = course_type.getResultObj().toString();
            allTypes = JSON.parseArray(courseTypeForJson,CourseType.class);
        }else{
            allTypes = putDataIntoRedis();
        }
        //1. 查询出所有的类型
        // List<CourseType> allTypes = baseMapper.selectList(null);
        //2. 创建list存放顶层节点
        List<CourseType> topNode = new ArrayList<>();
        //3.查询顶层节点
        for (CourseType everyType : allTypes) {
            if(everyType.getPid().longValue()==0){
                topNode.add(everyType);
            }else {
                //4. 当前节点是父节点
                CourseType currentParentNode = null;
                for (CourseType tempType : allTypes) {
                    if(everyType.getPid().longValue()==tempType.getId().longValue()){
                        currentParentNode = tempType;
                        break;
                    }
                }
                if(currentParentNode!=null){
                    currentParentNode.getChildren().add(everyType);
                }
            }
        }
        return topNode;
    }

    @Override
    public List<CourseTypeVO> crumbs(Long id) {
        List<CourseTypeVO> result = new ArrayList<>();
        CourseTypeVO courseTypeVO = new CourseTypeVO();
        //1. 根据id查询出数据
        CourseType courseType = baseMapper.selectById(id);
        String path = courseType.getPath();
        if (!path.isEmpty()) {
            path = path.startsWith(".") ? path.substring(1) : path;
            path = path.endsWith(".") ? path.substring(0, path.lastIndexOf(".")) : path;
            String[] paths = path.split("\\.");
            for (String onePath : paths) {
                CourseType courseTypeFromId = baseMapper.selectById(Long.valueOf(onePath));
                courseTypeVO.setOwnerProductType(courseTypeFromId);
                List<CourseType> courseTypeFromPid = baseMapper.selectByPid(courseType.getPid());
                courseTypeVO.setOtherProductTypes(courseTypeFromPid);
                //删除掉自身节点
                Iterator<CourseType> iterator = courseTypeFromPid.iterator();
                while (iterator.hasNext()) {
                    if (iterator.next().getPid().longValue() == courseTypeFromId.getPid()) {
                        iterator.remove();
                    }
                }
                result.add(courseTypeVO);
            }
        }
        return result;
    }

    /**
     * 添加
     * @param entity
     * @return
     */

    @Override
    public boolean insert(CourseType entity) {
        boolean insertResult = super.insert(entity);
        putDataIntoRedis();
        pageStaticAction();
        return insertResult;
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @Override
    public boolean deleteById(Serializable id) {
        boolean deleteResult = super.deleteById(id);
        putDataIntoRedis();
        pageStaticAction();
        return deleteResult;
    }

    /**
     * 根据id更新
     * @param entity
     * @return
     */
    @Override
    public boolean updateById(CourseType entity) {
        boolean updateResult = super.updateById(entity);
        putDataIntoRedis();
        pageStaticAction();
        return updateResult;
    }
}
